//
//  WNUserAccount.swift
//  XLWeibo
//
//  Created by 风不会停息 on 2017/7/25.
//  Copyright © 2017年 风不会停息. All rights reserved.
//

import UIKit

let UserAccountPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")

class WNUserAccount: NSObject,NSCoding{
    
    //访问令牌
    var access_token : String?
    
    //过期秒数
    var expires_in : Int = 0 {
        didSet{
            
            expiresDate = Date().addingTimeInterval(TimeInterval(expires_in))
        }
    }
    
    //过期时间
    var expiresDate:Date?
    
    //用户ID
    var uid : Int64 = 0
    
    //用户名字
    var  name : String?
    
    //用户头像
    var avatar_large : String?
    
    //kvc
    init(dic : [String : Any]){
        super.init()
        setValuesForKeys(dic)
    }
    
    // MARK:----归档解档
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token,forKey:"access_token")
        aCoder.encode(uid,forKey:"uid")
        aCoder.encode(expiresDate,forKey:"expiresDate")
        aCoder.encode(name,forKey:"name")
        aCoder.encode(avatar_large,forKey:"avatar_large")
    }
    
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey:"access_token") as? String
        uid = aDecoder.decodeInt64(forKey: "uid")
        expiresDate = aDecoder.decodeObject(forKey:"expiresDate") as? Date
        name = aDecoder.decodeObject(forKey:"name") as? String
        avatar_large = aDecoder.decodeObject(forKey:"avatar_large") as? String

    }
    
    //保存用户对象
    func saveUserAccount(){
        
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccountPath)
    }
    
    //读取用户对象
    class func loadUserAccount() -> WNUserAccount?{
        
        let userAccount = NSKeyedUnarchiver.unarchiveObject(withFile: UserAccountPath) as? WNUserAccount
        
        return userAccount
    }
    
    
    //空实现防崩溃
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    
    
    
    
    
}
